package com.xuecheng.learning.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
@Slf4j
public class MyCourseTablesServiceimpl implements MyCourseTablesService {

    @Autowired(required = false)
    private XcCourseTablesMapper xcCourseTablesMapper;
    @Autowired(required = false)
    private XcChooseCourseMapper xcChooseCourseMapper;
    @Autowired
    private ContentServiceClient contentServiceClient;
    /**
     * 添加选课记录表
     * @param courseId 课程id
     * @param userId 用户名
     * @param companyId 机构id
     * @return [{"code":"702001","desc":"正常学习"},
     * {"code":"702002","desc":"没有选课或选课后没有支付"},
     * {"code":"702003","desc":"已过期需要申请续期或重新支付"}]
     */
    @Override
    public XcChooseCourseDto addChooseCourse(Long courseId, String userId, Long companyId) {
        XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();

        //远程调用，查询已经审核通过的课程信息
        CoursePublish courseInfo = contentServiceClient.getCoursepublish(courseId);
        //收费规则
        String charge = courseInfo.getCharge();
        //查看之前是否已经拥有选课记录表
        LambdaQueryWrapper<XcChooseCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(XcChooseCourse::getCourseId,courseInfo.getId())
                .eq(XcChooseCourse::getUserId,userId);
        XcChooseCourse xc = xcChooseCourseMapper.selectOne(wrapper);

        if(charge.equals("201000")){
            //免费
            //添加选课记录
            XcChooseCourse xcChooseCourse = addChooseCourseTable(userId, courseInfo, companyId, "201000");

            //添加到我的课程
            XcCourseTables xcCourseTables = addFreeCourse(userId, courseInfo, companyId, xcChooseCourse);
            BeanUtils.copyProperties(xcCourseTables,xcChooseCourseDto);
            if(xc!=null){
                xcChooseCourseDto.setLearnStatus("{\"code\":\"702003\",\"desc\":\"已过期需要申请续期或重新支付\"}");
            }else {
                xcChooseCourseDto.setLearnStatus("{\"code\":\"702001\",\"desc\":\"正常学习\"}");
            }
            return xcChooseCourseDto;
        }else {
            //收费
            //添加选课记录
            XcChooseCourse xcChooseCourse = addChooseCourseTable(userId, courseInfo, companyId, "201001");
            //支付等操作


            //失败后
            if(false){
                xcChooseCourseDto.setLearnStatus("code\":\"702002\",\"desc\":\"没有选课或选课后没有支付\"");
                return xcChooseCourseDto;
            }
            //添加到我的课程
            XcCourseTables xcCourseTables = addFreeCourse(userId, courseInfo, companyId, xcChooseCourse);
            BeanUtils.copyProperties(xcCourseTables,xcChooseCourseDto);
            if(xc!=null){
                xcChooseCourseDto.setLearnStatus("{\"code\":\"702003\",\"desc\":\"已过期需要申请续期或重新支付\"}");
            }else {
                xcChooseCourseDto.setLearnStatus("{\"code\":\"702001\",\"desc\":\"正常学习\"}");
            }
            return xcChooseCourseDto;
        }
    }


    /**
     * @description 判断学习资格
     * @param userId
     * @param courseId
     * @return XcCourseTablesDto 学习资格状态 [{"code":"702001","desc":"正常学习"},{"code":"702002","desc":"没有选课或选课后没有支付"},{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
     * @author Mr.M
     * @date 2022/10/3 7:37
     */
    @Override
    public XcCourseTablesDto getLeanringStatus(String userId, Long courseId){
        //查询我的课程表
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
        if(xcCourseTables==null){
            XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
            //没有选课或选课后没有支付
            xcCourseTablesDto.setLearnStatus("702002");
            return xcCourseTablesDto;
        }
        XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
        BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);
        //是否过期,true过期，false未过期
        boolean isExpires = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if(!isExpires){
            //正常学习
            xcCourseTablesDto.setLearnStatus("702001");
            return xcCourseTablesDto;

        }else{
            //已过期
            xcCourseTablesDto.setLearnStatus("702003");
            return xcCourseTablesDto;
        }

    }
    /**
     * @description 根据课程和用户查询我的课程表中某一门课程
     * @param userId
     * @param courseId
     * @return com.xuecheng.learning.model.po.XcCourseTables
     * @author Mr.M
     * @date 2022/10/2 17:07
     */
    public XcCourseTables getXcCourseTables(String userId,Long courseId){
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, userId).eq(XcCourseTables::getCourseId, courseId));
        return xcCourseTables;

    }


    //加入到我的课程
    private XcCourseTables addFreeCourse(String userId, CoursePublish courseInfo, Long companyId,XcChooseCourse xcChooseCourse) {
        LambdaQueryWrapper<XcCourseTables> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(XcCourseTables::getCourseId,courseInfo.getId())
                .eq(XcCourseTables::getUserId,userId);
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(wrapper);
        if(xcCourseTables!=null){
            return  xcCourseTables;
        }
        xcCourseTables = new XcCourseTables();
        //选课记录id
        xcCourseTables.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTables.setUserId(userId);
        xcCourseTables.setCourseId(courseInfo.getId());
        xcCourseTables.setCompanyId(companyId);
        xcCourseTables.setCourseName(courseInfo.getName());
        xcCourseTables.setCreateDate(LocalDateTime.now());
        xcCourseTables.setValidtimeStart(LocalDateTime.now());
        xcCourseTables.setValidtimeEnd(LocalDateTime.now().plusYears(1));
        int insert = xcCourseTablesMapper.insert(xcCourseTables);

        if(insert<=0){
            XueChengPlusException.cast("添加我的课程表失败！");
        }
        return xcCourseTables;
    }

    //添加选课记录表
    private XcChooseCourse addChooseCourseTable(String userId, CoursePublish courseInfo, Long companyId,String orderType) {
        //查看之前是否已经拥有选课记录表
        LambdaQueryWrapper<XcChooseCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(XcChooseCourse::getCourseId,courseInfo.getId())
                        .eq(XcChooseCourse::getUserId,userId);
        XcChooseCourse xcChooseCourse = xcChooseCourseMapper.selectOne(wrapper);
        //更新选课记录表
        if(xcChooseCourse!=null){
            //价格--用于之后修改价格
            if(courseInfo.getPrice()==null)courseInfo.setPrice(0f);
            xcChooseCourse.setCoursePrice(courseInfo.getPrice());
            if(orderType.equals("201000")){
                //选课成功
                xcChooseCourse.setStatus("701001");
            }else{
                //待支付
                xcChooseCourse.setStatus("701002");
            }
            xcChooseCourse.setValidtimeStart(LocalDateTime.now());
            xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusYears(1));
            xcChooseCourseMapper.updateById(xcChooseCourse);
            return xcChooseCourse;
        }

        //新增
        xcChooseCourse=new XcChooseCourse();
        xcChooseCourse.setCourseId(courseInfo.getId());
        xcChooseCourse.setCourseName(courseInfo.getName());
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(companyId);
        xcChooseCourse.setOrderType(orderType);
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        //价格
        if(courseInfo.getPrice()==null)courseInfo.setPrice(0f);
        xcChooseCourse.setCoursePrice(courseInfo.getPrice());

        xcChooseCourse.setValidDays(365);
        if(orderType.equals("201000")){
            //选课成功
            xcChooseCourse.setStatus("701001");
        }else{
            //待支付
            xcChooseCourse.setStatus("701002");
        }
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusYears(1));

        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if(insert<=0){
            XueChengPlusException.cast("添加选课记录表失败！");
        }
        return xcChooseCourse;
    }
}
